package com.bsierp.struts.action.file;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.List;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFClientAnchor;
import org.apache.poi.hssf.usermodel.HSSFPatriarch;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

import com.bsierp.business.pojo.Employee;
import com.bsierp.business.pojo.User;
import com.bsierp.service.DownloadService;
import com.bsierp.util.Constants;
import com.bsierp.util.hibernate.HibernateSessionFactory;

public class DownloadServiceAction extends DispatchAction {

	/**
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 * 
	 *             Here is a demo to download one excel file that you assigned
	 */
	public ActionForward excelUser(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String[] employee_id = request.getParameterValues("EmployeeID");
		employee_id = employee_id == null ? new String[0] : employee_id;
		String fileName = System.currentTimeMillis() + "-data.xls";
		User u = (User) request.getSession().getAttribute(
				Constants.userLogin_sessionindex);
		String hql = "from  Employee em where em.user=:user ";
		String hqla = "  and em.employeeId in(";
		if (employee_id.length > 0) {
			int j = 0;
			for (int k = 0; k < employee_id.length; k++) {
				if (j == 0) {
					hqla = hqla + " " + employee_id[k];
				} else {
					hqla = hqla + "  ," + employee_id[k];
				}
				j++;
			}
			hqla = hqla + ")";
			hql = hql + hqla;
		}

		SessionFactory sessionFactory = HibernateSessionFactory
				.getSessionFactory();
		Session session = sessionFactory.openSession();
		// Transaction tx = null;
		HSSFWorkbook wb = new HSSFWorkbook(); // create new workbook object
		try {
			// tx = session.beginTransaction();
			Query q = session.createQuery(hql);
			q.setEntity("user", u);

			BufferedImage bufferImg = null;
			ByteArrayOutputStream byteArrayOut = null;
			HSSFSheet sheet = wb.createSheet(); // create new sheet for workbook
			HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
			// sheet.setColumnWidth(columnIndex, width) //设置列宽
			HSSFRow row;

			HSSFCell cell;
			// HSSFPatriarch patriarch;
			// HSSFClientAnchor anchor;
			String[] employee = { "", "", "", "", "", "", "", "", "", "", "",
					"", "", "", "", "", "", "" };// 初始化此数组用来存放员工的各个属性
			List l = q.list();
			for (int i = 0; i < l.size(); i++) {
				Employee em = (Employee) l.get(i);
				// employee[0]=em.getEmployeePhoto();
				employee[0] = em.getEmployeeId().toString();
				employee[1] = em.getEmployeeName();
				if (em.getEmployeeGender().toString().equals("1")) {
					employee[2] = "男";
				} else if (em.getEmployeeGender().toString().equals("2")) {
					employee[2] = "女";
				}
				employee[3] = em.getEmployeeAge().toString();

				employee[4] = em.getEmployeeBirthday();
				if (em.getEmployeeMerriage().toString().equals("1")) {
					employee[5] = "未婚";
				} else if (em.getEmployeeMerriage().toString().equals("2")) {
					employee[5] = "已婚";
				}
				employee[6] = em.getEducation().getEducationName();
				employee[7] = em.getEmployeeIdcard();
				employee[8] = em.getNativePlace().getNativeplaceName();
				employee[9] = em.getDepartment().getDepartmentName();
				employee[10] = em.getHireType().getHiretypeName();
				employee[11] = em.getEmployeeHiredate();
				employee[12] = em.getBank().getBankName();
				employee[13] = em.getEmployeeBankaccount();
				employee[14] = em.getEmployeePhone();
				employee[15] = em.getPosition().getPositionName();
				employee[16] = em.getProfession().getProfessionName();
				employee[17] = em.getEmployeeState().getEmployeestateName();

				row = sheet.createRow((short) i + 1); // create new row for
				// sheet 生成相应行
				row.setHeight((short) 900);// 设置行高
				// create cell,the number of the cell depends on the length of
				for (int j = 1; j <= employee.length; j++) {
					cell = row.createCell((short) (j)); // create cell
					cell.setCellValue(employee[j - 1]); // set the value for
					// cell

				}
				String file = request.getSession().getServletContext()
						.getRealPath(Constants.employee_photopath)
						+ "/" + em.getEmployeePhoto();
				byteArrayOut = new ByteArrayOutputStream();
				bufferImg = ImageIO.read(new File(file));
				ImageIO.write(bufferImg, "jpg", byteArrayOut);
				HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0, 1023, 255,
						(short) 0, i + 1, (short) 0, i + 1);
				anchor.setAnchorType(3);
				// 设置图片放置基本参数
				// 第一二个参数为图片左上角顶点在所在单元格里的点坐标，
				// 第三四个参数为图片右下角顶点在所在单元格里的点坐标，
				// 第五六个参数为图片左上角顶点所在单元格的坐标，
				// 第七八个参数为图片右下角顶点所在单元格的坐标
				patriarch.createPicture(anchor, wb.addPicture(byteArrayOut
						.toByteArray(), HSSFWorkbook.PICTURE_TYPE_JPEG));
				bufferImg.flush();
				byteArrayOut.flush();
				byteArrayOut.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			session.close();
			sessionFactory.close();
		}
		// download the user information as a excel file
		DownloadService.exportExcelFile(wb, fileName, request, response);

		return null;
	}
}
